from urllib import request
import urllib.error
import os, requests, sys, bz2, gzip
from lxml import html
import urllib.parse
import xml.dom.minidom



# PrimaryXmlAnalyze类
# 用于分析仓库元数据（repodata）中 primary.xml.gz文件
# 对外接口：
# 1、def fileinfo(cls, primaryfile) -> list:
#   detail: 将primary.xml.gz文件中，每一个包的信息，形成一个info
#         info = {
#             "name": 软件包名,
#             "version": 软件包版本,
#             "sha256": 软件包校验值,
#             "location": 软件包下载名,
#             "sourcerpm": 源码包名
#         }
#   return：（list） 由info组成的列表
class PrimaryXmlAnalyze:
    @classmethod
    def fileinfo(cls, primaryfile) -> list:
        fileinfos = []
        root = cls._read_primaryxml(primaryfile)
        for mumber in root.getElementsByTagName("package"):
            info = {
                "name": cls._name(mumber),
                "version": cls._version(mumber),
                "sha256": cls._sha256(mumber),
                "location": cls._location(mumber)[9:],
                "sourcerpm": cls._sourcerpm(mumber)
            }
            fileinfos.append(info)
        return fileinfos

    @classmethod
    def _read_primaryxml(cls, primaryfile):
        if primaryfile.endswith("bz2"):
            f = bz2.open(primaryfile, "rb", encoding='utf-8')
        elif primaryfile.endswith("gz"):
            f = gzip.open(primaryfile, 'rt', encoding='utf-8')
        else:
            print("sha256文件既不属于 bz2 ，也不属于 gz")
            sys.exit(0)
        content = f.read()
        root = xml.dom.minidom.parseString(content)
        return root

    @classmethod
    def _name(cls, root_package) -> str:
        name = root_package.getElementsByTagName("name")[0].firstChild.data
        return name

    @classmethod
    def _version(cls, root_package) -> str:
        ver = root_package.getElementsByTagName("version")[0].getAttribute("ver")
        rel = root_package.getElementsByTagName("version")[0].getAttribute("rel")
        return ver + "-" + rel

    @classmethod
    def _location(cls, root_package) -> str:
        # 提取 location 的 href 属性值
        location = root_package.getElementsByTagName('location')[0].getAttribute('href')
        return location

    @classmethod
    def _sha256(cls, root_package) -> str:
        checksum = root_package.getElementsByTagName('checksum')[0].firstChild.data
        return checksum

    @classmethod
    def _sourcerpm(cls, root_package) -> str:
        srcrpm = root_package.getElementsByTagName("format")[0].getElementsByTagName("rpm:sourcerpm")[0].firstChild.data
        return srcrpm

class PrimaryXmlFile:
    def download(self):
        pass
    
    def delete(self):
        pass